package com.lyhengtongwl.zqsnews.ui.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.base.BaseActivity;
import com.lyhengtongwl.zqsnews.entity.BaseEntity;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.net.Url;
import com.lyhengtongwl.zqsnews.utils.DataCheckUtils;
import com.lyhengtongwl.zqsnews.utils.SaveParameterUtils;
import com.lyhengtongwl.zqsnews.utils.ScreenUtil;
import com.lyhengtongwl.zqsnews.utils.TitleBuilder;
import com.lyhengtongwl.zqsnews.utils.ToastUtil;
import com.lyhengtongwl.zqsnews.widget.CountTimer;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

/**
 * 新用户微信登录绑定手机号
 */
public class BindMobileActivity extends BaseActivity {

    @BindView(R.id.et_phone)
    EditText etPhone;//手机号

    @BindView(R.id.et_codeImg)
    EditText etCodeImg;
    @BindView(R.id.iv_codeImg)
    ImageView iv_codeImg;//验证码图片

    @BindView(R.id.edit_phoneCode)
    EditText etPhoneCode;
    @BindView(R.id.tv_getcode)
    TextView tvGetCode;

    @BindView(R.id.edit_pwd)
    EditText etPwd;
    @BindView(R.id.iv_eye)
    ImageView ivEye;
    @BindView(R.id.edit_pwd2)
    EditText etPwd2;
    @BindView(R.id.iv_eye2)
    ImageView ivEye2;

    @BindView(R.id.cb_protocol)
    ImageView cb_protocol;

    @BindView(R.id.tv_bind)
    TextView tvBind;
    @BindView(R.id.ed_referralCode)//推介人代码
            EditText ed_referralCode;
    private boolean isGetCodeImg = true;//默认是刷新过图片验证码的
    CountTimer countTimer;

    //密码显示与隐藏
    boolean isShowPwd1 = true;//密码1
    boolean isShowPwd2 = true;//密码2
    private boolean isChecked = true;//是否已经同意 用户协议(默认同意)

    @Override
    public void setListen() {
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setBindStatus();
            }
        });
        etCodeImg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setBindStatus();
            }
        });

        etPhoneCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setBindStatus();
            }
        });
        etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setBindStatus();
            }
        });
        etPwd2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setBindStatus();
            }
        });


    }

    @Override
    public void setTitleBarColor() {
        new TitleBuilder(this).setTitleText("绑定手机号")
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_bind_mobile;
    }

    @Override
    public void initView() {
        countTimer = new CountTimer(tvGetCode);
    }

    @Override
    public void initData() {
        Picasso.with(App.getContext()).load(Url.BaseUrl + "/captcha/generateImage").memoryPolicy(MemoryPolicy.NO_CACHE).into(iv_codeImg);
    }

    @OnClick({R.id.iv_codeImg, R.id.tv_getcode, R.id.iv_eye, R.id.iv_eye2, R.id.cb_protocol, R.id.tv_bind, R.id.tv_xieyi})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.iv_codeImg://图片验证码
                refreshCodeImg();
                break;
            case R.id.tv_getcode://获取短信验证码
                if (!isGetCodeImg) {
                    refreshCodeImg();
                }
                if (TextUtils.isEmpty(etPhone.getText().toString().trim())) {
                    ToastUtil.showShort(App.getContext(), "请输入手机号");
                    return;
                }
                if (!DataCheckUtils.isCellphone(etPhone.getText().toString().trim())) {
                    ToastUtil.showShort(App.getContext(), "请输入正确的手机号");
                    return;
                }
                if (TextUtils.isEmpty(etCodeImg.getText().toString())) {
                    ToastUtil.showShort(App.getContext(), "请输入图片验证码！");
                    return;
                }
                sendVerify();
                break;
            case R.id.iv_eye://密码
                if (isShowPwd1) {//显示出来
                    ivEye.setImageResource(R.drawable.login_eye);
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {//隐藏起来
                    ivEye.setImageResource(R.drawable.login_eyehide);
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                isShowPwd1 = !isShowPwd1;
                break;
            case R.id.iv_eye2://确认密码
                if (isShowPwd2) {
                    ivEye2.setImageResource(R.drawable.login_eye);
                    etPwd2.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    ivEye2.setImageResource(R.drawable.login_eyehide);
                    etPwd2.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                isShowPwd2 = !isShowPwd2;
                break;
            case R.id.cb_protocol:
                if (isChecked) {//没有
                    cb_protocol.setImageResource(R.drawable.login_agree);
                } else {
                    cb_protocol.setImageResource(R.drawable.login_agree01);
                }
                isChecked = !isChecked;
                setBindStatus();
                break;
            case R.id.tv_bind://绑定
                if (etPwd.getText().toString().equals(etPwd2.getText().toString())) {
                    bindPhone();
                } else {
                    ToastUtil.showShort(this, "两次密码不一致！");
                }
                break;
            case R.id.tv_xieyi:
                startActivity(new Intent(BindMobileActivity.this, WebActivity.class).putExtra("title", "注册协议").putExtra("url", Url.REGISTER_AGREEMENT));
                break;
        }

    }

    //刷新图片验证码
    private void refreshCodeImg() {
        isGetCodeImg = true;
        etCodeImg.setText("");
        Picasso.with(App.getContext()).load(Url.BaseUrl + "/captcha/generateImage").memoryPolicy(MemoryPolicy.NO_CACHE).into(iv_codeImg);
    }

    /**
     * 获取验证码
     */
    private void sendVerify() {
        countTimer.start();
        isGetCodeImg = false;
        String phoneStr = etPhone.getText().toString().trim();
        Task.getApiService().sendPhoneCode(phoneStr, etCodeImg.getText().toString()).enqueue(new MyCallback<BaseEntity>(this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                if ("0".equals(response.body().getCode())) {
                    ToastUtil.showShort(App.getContext(), response.body().getMessage());
                }
            }

            @Override
            protected void onFailure(Throwable t) {
                ToastUtil.showShort(App.getContext(), "发送失败！");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countTimer != null) {
            countTimer.cancel();
            tvGetCode.setEnabled(true);
            tvGetCode.setText("获取验证码");
        }
    }

    /**
     * 设置绑定按钮状态
     */
    private void setBindStatus() {
        String phone = etPhone.toString().trim();
        String imgCode = etCodeImg.getText().toString().trim();
        String phoneCode = etPhoneCode.getText().toString().trim();
        String pwd1 = etPwd.getText().toString().trim();
        String pwd2 = etPwd2.getText().toString().trim();
        if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(imgCode) || TextUtils.isEmpty(phoneCode) ||
                TextUtils.isEmpty(pwd1) || TextUtils.isEmpty(pwd2) || !isChecked) {
            tvBind.setEnabled(false);
        } else {
            tvBind.setEnabled(true);
        }
    }

    /**
     * 绑定手机号
     */
    private void bindPhone() {
        String unionId = getIntent().getStringExtra("unionId");
        String mobile = etPhone.getText().toString().trim();
        String mobileCode = etPhoneCode.getText().toString().trim();
        String pwd = etPwd.getText().toString().trim();
        String signCode = ed_referralCode.getText().toString();
        Task.getApiService().bindingMobile(unionId, mobile, mobileCode, pwd, signCode).enqueue(new MyCallback<BaseEntity>(this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                ToastUtil.showShort(BindMobileActivity.this, response.body().getMessage());
                if ("0".equals(response.body().getCode())) {
                    //保存sessionId信息
                    String sessionId = response.body().getResult().getString("sessionId");
                    SaveParameterUtils.saveJseSessionId(sessionId);
                    finish();
                    if (LoginAndRegisterActivity.mAct != null) {
                        LoginAndRegisterActivity.mAct.finish();
                    }
                } else {
                    ToastUtil.showShort(BindMobileActivity.this, response.body().getMessage());
                }
            }

            @Override
            protected void onFailure(Throwable t) {
            }
        });
    }

    /*
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ToastUtil.showShort(this, "请绑定手机号");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }*/
}
